
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;
using JYJ.AiYard.StationManagement.TbDeparts;
using JYJ.AiYard.StationManagement.TbDeparts.Dtos;
using JYJ.AiYard.StationManagement.TbDeparts.DomainService;
using JYJ.AiYard.StationManagement.TbDeparts.Authorization;
using Abp.Organizations;
using Abp.Authorization.Users;
using JYJ.AiYard.StationManagement.TbUser.Dtos;
using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.YardCommonHald;

namespace JYJ.AiYard.StationManagement.TbDeparts
{
    /// <summary>
    /// TbDepart应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbDepartAppService : AiYardAppServiceBase, ITbDepartAppService
    {
        private readonly IRepository<TbDepart, long> _entityRepository;

        private readonly IRepository<JYJ.AiYard.StationManagement.TbUser.TbUser, long> _entityuserRepository;

        private readonly ITbDepartManager _entityManager;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbDepartAppService(
        IRepository<TbDepart, long> entityRepository,
        IRepository<JYJ.AiYard.StationManagement.TbUser.TbUser, long> entityuserRepository,
        ITbDepartManager entityManager,
        IAiYardDbTableIssuedCard aiYardDbTableIssuedCard
        )
        {
            _entityRepository = entityRepository;
            _entityuserRepository = entityuserRepository;
            _entityManager=entityManager;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
        }

        /// <summary>
        /// 获取所有的部门
        /// </summary>
        /// <returns></returns>
        public async Task<List<TbDepartListDto>> GetAllTbDepart(long StationId)
        {
            var tbDepart = await _entityRepository.GetAll().Where(o => o.Station_ID == StationId).ToListAsync();

            var allTbDepart = tbDepart.MapTo<List<TbDepartListDto>>();   // ObjectMapper.Map<ListResultDto<TbDepartListDto>>(tbdepart);

            return allTbDepart;
        }


        /// <summary>
        /// 获取TbDepart的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbDepartPermissions.Query)] 
        public async Task<PagedResultDto<TbDepartListDto>> GetPaged(GetTbDepartsInput input)
		{
			List<long> StationList = new List<long>();
			tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
			if (filterText.StationId == null || filterText.StationId <= 0)
			{
				StationList = GetCurrenUserOrganizationAndChildrenUnit();
			}
			else
			{
				StationList.Add((long)filterText.StationId);
			}
			var query = _entityRepository.GetAll().Where(o => StationList.Contains(o.Station_ID));
			// TODO:根据传入的参数添加过滤条件
            

			var count = await query.CountAsync();

			var entityList = await query               
                    .OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			// var entityListDtos = ObjectMapper.Map<List<TbDepartListDto>>(entityList);
			var entityListDtos =entityList.MapTo<List<TbDepartListDto>>();

			return new PagedResultDto<TbDepartListDto>(count,entityListDtos);
		}

        #region 获取部门用户树
        /// <summary>
        /// 获取当前组织的部门用户树
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetDepartUsersDto>> GetPepartUsersTree()
        {          
            var tbDepart = await _entityRepository.GetAll().Where(o => GetCurrenUserOrganizationAndChildrenUnit().Contains(o.Station_ID)).ToListAsync();

            var allTbDepart = tbDepart.MapTo<List<GetDepartUsersDto>>();
            foreach (GetDepartUsersDto tbdepart in allTbDepart)
            {
                var tuser = await _entityuserRepository.GetAll().Where(o => GetCurrenUserOrganizationAndChildrenUnit().Contains(o.Station_ID) && o.User_Dept == tbdepart.Id).ToListAsync();
                tbdepart.userDepartDto = tuser.MapTo<List<UserDepartDto>>();                
            }
           
            return allTbDepart;
        }
        #endregion


        /// <summary>
        /// 通过指定id获取TbDepartListDto信息
        /// </summary>
        [AbpAuthorize(TbDepartPermissions.Query)] 
		public async Task<TbDepartListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbDepartListDto>();
		}

		/// <summary>
		/// 获取编辑 TbDepart
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbDepartPermissions.Create,TbDepartPermissions.Edit)]
		public async Task<GetTbDepartForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbDepartForEditOutput();
            TbDepartEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbDepartEditDto>();

			}
			else
			{
				editDto = new TbDepartEditDto();
			}

			output.TbDepart = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbDepart的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbDepartPermissions.Create,TbDepartPermissions.Edit)]
		public async Task CreateOrUpdate(CreateOrUpdateTbDepartInput input)
		{
            if (input.TbDepart.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            }
            if (input.TbDepart.Id.HasValue)
			{
				await Update(input.TbDepart);
			}
			else
			{
				await Create(input.TbDepart);
			}
		}


		/// <summary>
		/// 新增TbDepart
		/// </summary>
		[AbpAuthorize(TbDepartPermissions.Create)]
		protected virtual async Task<TbDepartEditDto> Create(TbDepartEditDto input)
		{
            //TODO:新增前的逻辑判断，是否允许新增 
            if (input.Depart_Id > 0)
            {
                //获取上级部门代码
                var prequery = await _entityRepository.GetAsync(input.Depart_Id.Value);
                input.Depart_PCode = prequery.Depart_Code;
            }
            // var entity = ObjectMapper.Map <TbDepart>(input);
            var entity=input.MapTo<TbDepart>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<TbDepartEditDto>();
		}

		/// <summary>
		/// 编辑TbDepart
		/// </summary>
		[AbpAuthorize(TbDepartPermissions.Edit)]
		protected virtual async Task Update(TbDepartEditDto input)
		{
            //TODO:更新前的逻辑判断，是否允许更新
            //获取上级部门代码
            var prequery = await _entityRepository.GetAsync(input.Depart_Id.Value);
            input.Depart_PCode = prequery.Depart_Code;

            var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除TbDepart信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbDepartPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
            if (_aiYardDbTableIssuedCard.CheckIsForeignKey(input.Id, 0, "Depart"))
            {
                throw new Exception(input.Id + "存在外键约束，不允许删除");
            }
            //TODO:删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbDepart的方法
		/// </summary>
		[AbpAuthorize(TbDepartPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
        {
            foreach (long Id in input)
            {
                if (_aiYardDbTableIssuedCard.CheckIsForeignKey(Id, 0, "Depart"))
                {
                    throw new Exception(Id + "存在外键约束，不允许删除");
                }
            }
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		///// <summary>
		///// 导出TbDepart为excel表,等待开发。
		///// </summary>
		///// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


